package io.github.source.media.bean;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import okhttp3.internal.platform.Platform;
import okio.AsyncTimeout;

import static java.util.concurrent.TimeUnit.MILLISECONDS;


/**
 * @ClassName: RealMediaCall
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author: huangrongcai
 * @date: 2024/6/24
 * @Copyright: 黄嵘才（HuangRc)
 */
class RealMediaCall implements MediaCall {
    public static MediaCall newRealCall(AMedia aMedia, MediaQuery originalQuery) {
        RealMediaCall call = new RealMediaCall(aMedia, originalQuery);
        call.eventListener = aMedia.eventListenerFactory.create(call);
        return call;
    }
    // Guarded by this.
    private boolean executed;
    final AMedia aMedia;
    final MediaQuery originalQuery;
    @Nullable
    MediaEventListener eventListener;
    final AsyncTimeout timeout;

    RealMediaCall(AMedia aMedia, MediaQuery query) {
        this.aMedia = aMedia;
        this.originalQuery = query;

        this.timeout = new AsyncTimeout() {
            @Override protected void timedOut() {
                cancel();
            }
        };
        this.timeout.timeout(aMedia.callTimeoutMillis(), MILLISECONDS);

    }
    private void captureCallStackTrace() {
        Object callStackTrace = Platform.get().getStackTraceForCloseable("response.body().close()");
    }
    @Override
    public MediaQuery query() {
        return originalQuery;
    }

    @Override
    public MediaResult execute() throws IOException {
        synchronized (this) {
            if (executed) throw new IllegalStateException("Already Executed");
            executed = true;
        }
        captureCallStackTrace();
        timeout.enter();
        eventListener.callStart(this);
        try {
            MediaResult result = getResponseWithInterceptorChain();
            if (result == null) throw new IOException("Canceled");
            return result;
        } catch (IOException e) {
            e = timeoutExit(e);
            eventListener.callFailed(this, e);
            throw e;
        } finally {
        }
    }

    @Override
    public void cancel() {

    }
    @Nullable IOException timeoutExit(@Nullable IOException cause) {
        if (!timeout.exit()) return cause;

        InterruptedIOException e = new InterruptedIOException("timeout");
        if (cause != null) {
            e.initCause(cause);
        }
        return e;
    }
    MediaResult getResponseWithInterceptorChain() throws IOException {
        // Build a full stack of interceptors.
        List<MediaProvider> interceptors = new ArrayList<>();
        interceptors.addAll(aMedia.interceptors());

        return null;
    }
}
